import React, { useState } from 'react'
import { Tree } from 'antd'
import './style.scss'
import Search from 'antd/lib/input/Search'

function OrgTree (props) {
  const [expandedKeys, setExpandedKeys] = useState([])
  const [autoExpandParent, setAutoExpandParent] = useState(false)
  const treeData = [
    {
      title: '根组织',
      key: '1',
      children: [
        {  
          title: '组织1',
          key: '1-1',
          children: [
            {  
              title: '组织12',
              key: '1-1-1',
            }
          ]
        },
        {  
          title: '组织2',
          key: '1-2',
          children: [
            {  
              title: '组织22',
              key: '1-1-2',
            }
          ]
        }
      ]
    }
  ]
  const dataList = [];
  const generateList = data => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const { key } = node;
      dataList.push({ key, title: key });
      if (node.children) {
        generateList(node.children);
      }
    }
  }
  generateList(treeData)
  const getParentKey = (key, tree) => {
    let parentKey
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i]
      if (node.children) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.key
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children)
        }
      }
    }
    return parentKey
  };
  const onChange = e => {
    const { value } = e.target;
    const expandedKeys = dataList
      .map(item => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, treeData)
        }
        return null
      })
      .filter((item, i, self) => item && self.indexOf(item) === i)
    /* this.setState({
      expandedKeys,
      searchValue: value,
      autoExpandParent: true,
    }) */
    setExpandedKeys(expandedKeys)
    setAutoExpandParent(true)
  }
  const onExpand = expandedKeys => {
    setExpandedKeys(expandedKeys)
    setAutoExpandParent(false)
  }
  return (
    <div className="org-tree-box">
      <Search style={{ marginBottom: 8 }} placeholder="Search" onChange={onChange} />
      <Tree
        showLine={true}
        treeData={treeData}
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
      />
    </div>
  )
}

export default  OrgTree
